<template>
  <div class="app-container">
    <el-card class="card">
      <!-- <div slot="header">
        <span>汇总信息</span>
      </div> -->
      <el-row>
        <el-col :span="4">
          <span style="font-size:14px; font-weight: bold;">当前总成交</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ currentScore / 100 }}元</span>
          </div>
        </el-col>
        <el-col :span="3">
          <span style="font-size:14px; font-weight: bold;">总限额</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ limitScore / 100 }}元</span>
          </div>
        </el-col>
        <el-col :span="4">
          <span style="font-size:14px; font-weight: bold;">剩余金额</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ restScore / 100 }}元</span>
          </div>
        </el-col>
        <el-col :span="3">
          <span style="font-size:14px; font-weight: bold;">总单数</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ orderSize }}</span>
          </div>
        </el-col>
        <el-col :span="4">
          <span style="font-size:14px; font-weight: bold;">成交单数</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ doneSize }}</span>
          </div>
        </el-col>
        <el-col :span="3">
          <span style="font-size:14px; font-weight: bold;">店铺数</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ storeSize }}</span>
          </div>
        </el-col>
        <el-col :span="3">
          <span style="font-size:14px; font-weight: bold;">利率</span>
          <div style="padding-top:8px">
            <span style="font-size:11px;">{{ interestRate }} %</span>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-row>
      <el-col :span="17">
        <el-row type="flex" align="bottom" justify="space-between">
          <el-col :span="14">
            <h5>店铺</h5>
          </el-col>
          <el-col :span="10">
            <div class="toop-bar">
              <el-button-group>
                <el-button size="mini" type="primary" @click="setScore">批量限额</el-button>
                <el-button size="mini" type="primary" @click="startAll">全部开启</el-button>
                <el-button size="mini" type="primary" @click="stopAll">全部结束</el-button>
                <el-button size="mini" type="warning" @click="refeshData">手动刷新</el-button>
              </el-button-group>
            </div>
          </el-col>
        </el-row>
        <el-table
          :data="stores"
          size="mini"
          border
          height="540px"
          highlight-current-row
          @row-click="handleStoreRowClick"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column label="店铺ID" align="center" min-width="9%">
            <template slot-scope="{row}">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="店名" align="center" min-width="12%">
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品数" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ row.goods_size }}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额上限" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ row.score / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成交金额" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ row.used_score / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="剩余金额" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ (row.score - row.used_score) / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单量限制" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ row.order_size_limit }}</span>
            </template>
          </el-table-column>
          <el-table-column label="锁定单量" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ row.not_pay_size }}</span>
            </template>
          </el-table-column>
          <el-table-column label="轮询单数" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span>{{ row.loop_size }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成交单数" align="center" min-width="6%">
            <template slot-scope="{row}">
              <span v-if="row.done_size >= row.order_size_limit - 2" style="color:red">{{ row.done_size }}</span>
              <span v-else>{{ row.done_size }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="6%" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-switch
                v-model="row.loop"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="toggleStoreLoop(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="6%" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-tag size="mini" effect="dark" type="success" @click="handleEditStore(row)">修改</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="7" style="padding-left: 8px;">
        <h5>商品</h5>
        <el-table
          :data="goodses"
          size="mini"
          border
          height="540px"
          highlight-current-row
        >
          <el-table-column label="ID" align="center" min-width="30%">
            <template slot-scope="{row}">
              <a
                :href="'https://mobile.yangkeduo.com/goods.html?goods_id='+row.id"
                target="_blank"
                style="color: blue;"
              >
                {{ row.id }}
              </a>
            </template>
          </el-table-column>
          <el-table-column label="价格" align="center" min-width="16%">
            <template slot-scope="{row}">
              <span>{{ row.price / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="轮询量" align="center" min-width="17%">
            <template slot-scope="{row}">
              <span>{{ row.loop_times }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成交量" align="center" min-width="17%">
            <template slot-scope="{row}">
              <span>{{ row.done_times }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" min-width="17%" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-tag :type="row.group_order_id ? 'info':'success' " size="mini" effect="dark" @click="handleGetOrderId(row)">下单</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column label="状态" align="center" min-width="20%">
            <template slot-scope="{row}">
              <el-switch
                v-model="row.loop"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="toggleGoodsLoop(row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog
      :visible.sync="dialogModifyStoreVisible"
      title="商店信息修改"
      width="40%"
    >
      <el-form label-width="80px" :model="formEditStore">
        <el-form-item label="限额">
          <el-input v-model="formEditStore.score" style="width:300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formEditStore.loop" placeholder="请设置状态" style="width:300px">
            <el-option label="生效" value="true" />
            <el-option label="无效" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="formEditStore.userId" placeholder="请设置负责人" style="width:300px">
            <el-option
              v-for="item in allUser"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModifyStoreVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFormEditStore">提交</el-button>
      </span>
    </el-dialog>
    <audio ref="overLimitAudio" src="@/assets/audio/overOrderLimit.mp3" />
  </div>
</template>

<script>
import { getUserCountInfo } from '@/api/count'
import { fetchStoreDetail as fetchStore, startAllStore, stopAllStore, getAllUser } from '@/api/user'
import { setLoop, setScore, editStore } from '@/api/store'
import { getList as getGoodsList, setLoop as setGoodsLoop, getOrderId, setOrderId } from '@/api/goods'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'

export default {
  name: 'CodeMurchnt',
  data() {
    return {
      currentScore: 0,
      limitScore: 0,
      restScore: 0,
      orderSize: 0,
      doneSize: 0,
      storeSize: 0,
      interestRate: 0,
      allUser: [],
      stores: [],
      multipleSelection: [],
      goodses: [],
      dialogModifyStoreVisible: false,
      formEditStore: {
        score: 0,
        loop: 'false',
        old_loop: 'false',
        userId: '',
        storeId: ''
      }
    }
  },
  computed: mapGetters({
    rootUserId: 'id',
    roles: 'roles'
  }),
  created() {
    this.getUserCountInfo()
    this.getStores()
    getAllUser().then(response => {
      const list = response.data
      this.allUser = list
    })
    const timer = setInterval(() => this.refeshData(), 90 * 1000)
    // 清理定时器
    this.$once('hook:beforeDestroy', () => { clearInterval(timer) })
  },
  methods: {
    refeshData() {
      this.getUserCountInfo()
      this.getStores()
    },
    getUserCountInfo() {
      getUserCountInfo(this.rootUserId).then(response => {
        const { currentScore, limitScore, orderSize, doneSize, storeSize, interestRate } = response.data
        this.currentScore = currentScore
        this.limitScore = limitScore
        const restScore = this.limitScore - this.currentScore
        this.restScore = restScore > 0 ? restScore : 0
        this.orderSize = orderSize
        this.doneSize = doneSize
        this.storeSize = storeSize
        this.interestRate = interestRate
      })
    },
    getStores() {
      fetchStore(this.rootUserId).then(response => {
        const stores = response.data.sort((a, b) => a.order_index - b.order_index)
        const warningStore = stores.filter(row => row.done_size >= row.order_size_limit - 1 && row.loop)
        if (warningStore.length && warningStore.length > 0) {
          this.$refs['overLimitAudio'].play()
        }
        this.stores = stores
      })
    },
    setScore() {
      if (this.multipleSelection.length === 0) {
        Message.warning('请选择数据!')
        return
      }
      this.$prompt('请输入限额（元）', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '只能输入数字'
      }).then(({ value }) => {
        const userScore = this.limitScore
        const score = this.multipleSelection.length * value * 100
        if (score > userScore) {
          Message.warning({
            message: `超出总限额，
          指定店铺数量：${this.multipleSelection.length},
          您的限额： ${score / 100}, 
          上级指定总限额：${userScore / 100}`,
            duration: 5000
          })
          return
        }
        setScore(this.multipleSelection.map(i => i.id), value * 100).then(_ => {
          Message.success('操作成功')
          this.getStores()
          this.getUserCountInfo()
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleStoreRowClick(row) {
      getGoodsList({
        store_id: row.id,
        page: 1,
        limit: 50
      }).then(response => {
        this.goodses = response.data.list
      })
    },
    startAll() {
      startAllStore(this.rootUserId).then(() => {
        Message.success('操作成功')
        this.getStores()
        this.getUserCountInfo()
      })
    },
    stopAll() {
      stopAllStore(this.rootUserId).then(() => {
        Message.success('操作成功')
        this.getStores()
        this.getUserCountInfo()
      })
    },
    toggleStoreLoop(row) {
      setLoop(row.id, row.loop, this.rootUserId).then(response => {
        Message.success('设置成功')
        this.getStores()
        this.getUserCountInfo()
      })
    },
    toggleGoodsLoop(row) {
      setGoodsLoop(row.id, row.loop).then(response => Message.success('设置成功'))
    },
    handleEditStore(row) {
      this.formEditStore.score = row.score / 100
      this.formEditStore.loop = `${row.loop}`
      this.formEditStore.old_loop = `${row.loop}`
      this.formEditStore.userId = this.rootUserId
      this.formEditStore.storeId = row.id
      this.dialogModifyStoreVisible = true
    },
    handleGetOrderId(row) {
      if (!row.group_order_id) {
        getOrderId(row.group_id1, row.price1, row.id, row.sku_id).then(resp => {
          if (resp.status === 200) {
            if (resp.data.code === 200) {
              setOrderId(row.id, resp.data.data.group_order_id).then(rs => {
                getGoodsList({
                  store_id: row.store_id,
                  page: 1,
                  limit: 50
                }).then(response => {
                  this.goodses = response.data.list
                })
                Message.success('设置成功')
              })
            } else {
              Message.warning('下单失败')
            }
          } else {
            Message.warning('下单失败')
          }
        })
      }
    },
    submitFormEditStore() {
      editStore(this.formEditStore).then(resp => {
        Message.success('操作成功')
        this.getStores()
        this.getUserCountInfo()
        this.dialogModifyStoreVisible = false
      })
    }
  }
}
</script>

<style scoped>
</style>
